package cn.stazxr.service.impl;

import cn.stazxr.domain.Role;
import cn.stazxr.domain.User;
import cn.stazxr.domain.UserAndRole;
import cn.stazxr.mapper.RoleMapper;
import cn.stazxr.mapper.UserMapper;
import cn.stazxr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;


    public List<User> list() {
        List<User> userList = userMapper.findAll();
        //封装userList中的每一个User的roles数据
        for (User user : userList) {
            //获得user的id
            Integer id = user.getId();
            //将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roles = roleMapper.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }

    public void save(User user, Integer[] roleIds) {
        //第一步 向sys_user表中存储数据
        int userId = userMapper.save(user);
        //第二步 向sys_user_role 关系表中存储多条数据
        for (Integer roleId : roleIds) {
            userMapper.saveUserRoleRel(user.getId(), roleId);
        }
    }

    public void del(Integer userId) {
        //1、删除sys_user_role关系表
        userMapper.delUserRoleRel(userId);
        //2、删除sys_user表
        userMapper.del(userId);
    }


    public Boolean login(User user) {
        User userdb = this.userMapper.getUser(user.getUsername());
        if (userdb != null) {
            if (userdb.getPassword().equals(user.getPassword())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int addUser(User user) {
        int i = userMapper.addUser(user);
        UserAndRole userAndRole = new UserAndRole();
        userAndRole.setUserId(user.getId());
        userAndRole.setRoleId(4);
        userMapper.addUserAndRole(userAndRole);
        return i;
    }

    @Override
    public boolean UserIsExisted(User user) {
        return userMapper.UserIsExisted(user) > 0 ? true : false;
    }

    @Override
    public List<User> serch(String username) {
        List<User> userList = userMapper.serch(username);
        //封装userList中的每一个User的roles数据
        for (User user : userList) {
            //获得user的id
            Integer id = user.getId();
            //将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roles = roleMapper.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }


}
